package com.example.oauth2.config;

import com.example.oauth2.domain.JiuBoDouResourceOwnerPasswordTokenGranter;
import com.example.oauth2.domain.JiuBoDouTokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.provider.CompositeTokenGranter;
import org.springframework.security.oauth2.provider.TokenGranter;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;

import javax.sql.DataSource;
import java.util.ArrayList;

/**
 * @ClassName JiuBoDouOauth2Config
 * @Description
 * @Author huyingliang
 * @Date 2024-02-29 16:11
 */
/*修改DefaultOAuth2RequestFactory中的 clientDetailsService*/
@Configuration
public class JiuBoDouOauth2Config extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private DataSource dataSource;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    /*使用 jdbc 来查询数据库中的 client 信息*/
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        JdbcClientDetailsService jdbcClientDetailsService = new JdbcClientDetailsService(dataSource);
        clients.withClientDetails(jdbcClientDetailsService);
    }


    @Autowired
    private JiuBoDouTokenService jiuBoDouTokenService;

    /*添加自己的 TokenGranter*/
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {

        ArrayList<TokenGranter> tokenGranters = new ArrayList<>();

        JiuBoDouResourceOwnerPasswordTokenGranter jiuBoDouResourceOwnerPasswordTokenGranter =
                new JiuBoDouResourceOwnerPasswordTokenGranter(
                        authenticationManager,
                        jiuBoDouTokenService,
                        endpoints.getClientDetailsService(),
                        endpoints.getOAuth2RequestFactory()
                );

        tokenGranters.add(jiuBoDouResourceOwnerPasswordTokenGranter);

        CompositeTokenGranter compositeTokenGranter = new CompositeTokenGranter(tokenGranters);

        endpoints.tokenGranter(compositeTokenGranter);
    }

}
